package heven.holt.wan.android.paging.source

import androidx.paging.PagingSource
import androidx.paging.PagingState
import heven.holt.wan.android.api.ApiWanArticleServer
import heven.holt.wan.android.model.ArticleModel

class WanArticleProjectPagingSource(
    private val apiWanArticleServer: ApiWanArticleServer,
    private val cid: Int
) : PagingSource<Int, ArticleModel>() {
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ArticleModel> = try {
        val page = params.key ?: 0
        val response = apiWanArticleServer.listProjectArticle(page, cid)
        val datas = response.data?.datas?.toMutableList() ?: mutableListOf()
        val curPage = response.data?.curPage ?: 1
        LoadResult.Page(
            data = datas,
            prevKey = if (curPage <= 1) null else page - 1,
            nextKey = if (curPage >= response.data?.pageCount ?: 0) null else page + 1
        )
    } catch (e: Exception) {
        LoadResult.Error(e)
    }

    override fun getRefreshKey(state: PagingState<Int, ArticleModel>): Int? = null
}